package org.truenewx.tnxjee.repo.jdbc.init;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.sql.init.SqlDataSourceScriptDatabaseInitializer;
import org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties;
import org.springframework.core.io.Resource;
import org.truenewx.tnxjee.core.io.ApplicationRootResourcePatternLoader;

public class ListenableSqlDataSourceScriptDatabaseInitializer extends SqlDataSourceScriptDatabaseInitializer {

    private DataSourceInitializeListener listener;

    public ListenableSqlDataSourceScriptDatabaseInitializer(DataSource dataSource,
            SqlInitializationProperties properties, ObjectProvider<DataSourceInitializeListener> listenerProvider) {
        super(dataSource, properties);
        setResourceLoader(new ApplicationRootResourcePatternLoader());
        this.listener = listenerProvider.getIfAvailable();
    }

    @Override
    protected void runScripts(Scripts scripts) {
        if (this.listener != null) {
            List<Resource> resources = new ArrayList<Resource>();
            for (Resource resource : scripts) {
                if (resource.exists() && this.listener.isExecutable(getDataSource(), resource)) {
                    resources.add(resource);
                }
            }
            if (!resources.isEmpty()) {
                scripts = new Scripts(resources).continueOnError(scripts.isContinueOnError())
                        .separator(scripts.getSeparator()).encoding(scripts.getEncoding());
            }
        }
        if (scripts.iterator().hasNext()) {
            super.runScripts(scripts);
            if (this.listener != null) {
                this.listener.afterRun(scripts);
            }
        }
    }

}
